import request from '../utils/request';
import config from '../utils/config';
import { eventChannel } from 'dva/saga';

export async function fetchImUsers(shopId, data) {
  return await request(`/shop/${shopId}/fetchImUser`, {
    method: 'post',
    body: {
      page: data.page || 1,
      pageSize: data.pageSize || 20,
      filter: data.filter ? JSON.stringify(data.filter) : undefined,
      sort: data.sort ? JSON.stringify(data.sort) : undefined,
    },
  });
}

export async function fetchVipImUser(shopId, cardNo) {
  return await request(`/shop/${shopId}/imUser/${encodeURIComponent(cardNo)}`, {
    params: {
      type: 1,
    },
  });
}

export async function fetchSalemanImUser(shopId, saleId) {
  return await request(`/shop/${shopId}/imUser/${encodeURIComponent(saleId)}`, {
    params: {
      type: 2,
    },
  });
}

export async function fetchImMessages(shopId, data) {
  return await request(`/shop/${shopId}/imMessage`, {
    params: {
      page: data.page || 1,
      pageSize: data.pageSize || 200,
      filter: data.filter ? JSON.stringify(data.filter) : undefined,
      sort: data.sort ? JSON.stringify(data.sort) : undefined,
    },
  });
}

export async function createImMessage(shopId, data) {
  return await request(`/shop/${shopId}/imMessage`, {
    method: 'post',
    body: {
      type: data.type || 1,
      content: data.content,
      senderId: data.senderId,
      targetId: data.targetId,
    },
  });
}

export async function readImMessage(shopId, messageIds = []) {
  return await request(`/shop/${shopId}/imMessage`, {
    method: 'post',
    body: {
      action: 'read',
      messageIds,
    },
  });
}

export async function initIMClient(imToken, onReceiveMessage, isSaga = false) {
  const RongIMLib = window.RongIMLib || {};
  const RongIMClient = RongIMLib.RongIMClient;
  const appKey = config.im.appKey;
  if (RongIMLib && appKey && imToken) {
    const setupStatus = () => {
      // 设置连接监听状态 （ status 标识当前连接状态 ）
      // 连接状态监听器
      RongIMClient.setConnectionStatusListener({
        onChanged: (status) => {
          switch (status) {
            case RongIMLib.ConnectionStatus.CONNECTED:
              console.log('IM链接成功');
              break;
            case RongIMLib.ConnectionStatus.CONNECTING:
              console.log('IM正在链接');
              break;
            case RongIMLib.ConnectionStatus.DISCONNECTED:
              console.log('IM断开连接');
              break;
            case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
              console.log('IM其他设备登录');
              break;
            case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
              console.log('IM域名不正确');
              break;
            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
              console.log('IM网络不可用');
              break;
          }
        },
      });
    };
    const listen = (callback) => {
      // 消息监听器
      RongIMClient.setOnReceiveMessageListener({
        // 接收到的消息
        onReceived: (message) => {
          if (!callback) {
            return;
          }
          // 判断消息类型
          switch (message.messageType) {
            case RongIMClient.MessageType.TextMessage:
              // message.content.content => 消息内容
              callback(1, message.content.content, message);
              break;
            case RongIMClient.MessageType.VoiceMessage:
              // 对声音进行预加载
              // message.content.content 格式为 AMR 格式的 base64 码
              break;
            case RongIMClient.MessageType.ImageMessage:
              // message.content.content => 图片缩略图 base64。
              // message.content.imageUri => 原图 URL。
              break;
            default:
            // do something...
          }
        },
      });
    };
    const connect = (resolve) => {
      resolve = resolve || (function empty() { });
      RongIMClient.connect(imToken, {
        onSuccess: (userId) => {
          resolve();
        },
        onTokenIncorrect: () => {
          resolve('IM token无效');
        },
        onError: (errorCode) => {
          let info = '';
          switch (errorCode) {
            case RongIMLib.ErrorCode.TIMEOUT:
              info = '超时';
              break;
            case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
              info = '不可接受的协议版本';
              break;
            case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
              info = 'appkey不正确';
              break;
            case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
              info = '服务器不可用';
              break;
          }
          resolve(info);
        },
      });

      const reconnectCallback = {
        onSuccess: (userId) => {
          console.log("IM重连成功." + userId);
        },
        onTokenIncorrect: () => {
          console.log('IM token无效');
        },
        onError: (errorCode) => {
          console.log("IM重连错误" + errorCode);
        },
      };
      const reconnectConfig = {
        // 默认 false, true 启用自动重连，启用则为必选参数
        auto: true,
        // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
        url: 'cdn.ronghub.com/RongIMLib-2.2.6.min.js',
        // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
        rate: [100, 1000, 3000, 6000, 10000, 20000, 30000, 60000, 120000, 300000],
      };
      RongIMClient.reconnect(reconnectCallback, reconnectConfig);

    };
    RongIMClient.init(config.im.appKey);
    setupStatus();

    if (isSaga) {
      let emitter;
      listen((type, content, message) => {
        if (emitter) {
          emitter({ type, content, message });
        }
      });
      connect();
      return eventChannel(eventEmitter => {
        emitter = eventEmitter;
      });
    } else {
      return new Promise((resolve) => {
        listen(onReceiveMessage);
        connect(resolve);
      });
    }
  }
}
